/** *******************************************************************
 * FlexDatabaseManager
 * @author  Jonnie Spratley
 * @contact jonniespratley@gmail.com
 * @internal
 ******************************************************************* */
package com.jonniespratley.flexdatabasemanager.commands.system
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.commands.SequenceCommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.flexdatabasemanager.business.FlexDatabaseManagerDelegate;
	import com.jonniespratley.flexdatabasemanager.events.system.PollConnectionUsageEvent;
	import com.jonniespratley.flexdatabasemanager.events.system.PollSQLQueriesEvent;
	import com.jonniespratley.flexdatabasemanager.model.ModelLocator;
	import com.jonniespratley.flexdatabasemanager.vo.*;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class PollConnectionUsageCommand extends SequenceCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		override public function execute( event:CairngormEvent ) : void
		{
			model.interactingWithServer = true;
			var evt:PollConnectionUsageEvent = event as PollConnectionUsageEvent;
			
			//this.nextEvent = evt.nextEventSequence;
			var delegate:FlexDatabaseManagerDelegate = new FlexDatabaseManagerDelegate( this );
				delegate.pollConnections( model.currentUser );
		}

		public function result( data:Object ) : void
		{ 
			model.interactingWithServer = false;
			var result:ResultEvent = data as ResultEvent;
			
			if ( data.result is String )
			{
				//get the raw JSON data and cast to String
				var rawData:String = String( data.result );
				
				//decode the data to ActionScript 
				var tempArray:Array = ( JSON.decode( data.result ) as Array );
				
				for ( var i:uint = 0; i < tempArray.length; i++ )
				{
					trace ( new ConnectionVO( tempArray[ i ] ) );	
				}
						
				
				
				//add the the model
			//	model.mysqlPollingConnectionCollection.addItem( o ); 		
			}
			
			PollSQLQueriesEvent( nextEvent );
			executeNextCommand()
		}

		public function fault( fault:Object ):void
		{
			model.interactingWithServer = false;
			
			var faultEvt:FaultEvent = fault as FaultEvent;
			Alert.show(faultEvt.fault.toString(), "Error");
			trace(faultEvt.fault.faultString);
		}

	}
}